<template>
  <div class="flex items-center">
    <div class="mr-4">数据上传:</div>
    <div class="flex">
      <a-upload :file-list="fileList" :before-upload="beforeUpload" @remove="handleRemove">
        <a-button>
          <upload-outlined></upload-outlined>
          上传文件
        </a-button>
      </a-upload>
    </div>
  </div>
</template>

<script setup lang="ts">
import { UploadOutlined } from '@ant-design/icons-vue'
import { read, utils, writeFile } from 'xlsx'

const fileList = ref<any[]>([])

const beforeUpload = (file: File) => {
  fileList.value = [file]
  getExcelData(file).then(exportExcelData)
  return false
}
const handleRemove = (file: any) => {
  const index = fileList.value?.indexOf(file) ?? -1
  const newFileList = fileList.value?.slice()
  newFileList.splice(index, 1)
  fileList.value = newFileList
}
const getExcelData = (file: File) => {
  console.log('🚀 ~ file:', file)
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = () => {
      const fileData = reader.result
      const wb = read(fileData, { type: 'binary', cellDates: true, codepage: 936 })
      console.log('🚀 ~ wb:', wb)
      const sheetJson: any = utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]], { header: 1 })
      console.log('🚀 ~ sheetJson:', sheetJson)
      resolve(sheetJson)
    }
    reader.readAsBinaryString(file)
    reader.onerror = reject
  })
}
const exportExcelData = (data: any) => {
  const Header = [
    [
      '序号',
      '公司',
      '二级单位',
      '三级单位',
      '监测设施名称',
      '装置',
      '设备名称',
      '设备类型',
      '设备编号',
      '测点名称',
      '单位',
      '测点类型',
      '节点ID',
      '报警门限(高高限)',
      '报警门限(高限)',
      '报警门限(低限)',
      '报警门限(低低限)',
      '位置经度',
      '位置纬度',
    ],
  ]
  const headerWs = utils.aoa_to_sheet(Header)
  const ws = utils.sheet_add_json(headerWs, data, { skipHeader: true, origin: 'A2' })

  /* 新建空workbook，然后加入worksheet */
  const wb = utils.book_new()

  // 可以自定义下载之后的sheetname
  utils.book_append_sheet(wb, ws, 'sheetName')

  /* 生成xlsx文件 */
  writeFile(wb, '下载.xlsx')
}
</script>

<style scoped lang="scss"></style>
